package com.coocaa.aries.jmeter.thread;

import com.coocaa.aries.jmeter.constant.StreamTypeConstants;
import com.coocaa.aries.jmeter.enums.ExecStatusEnums;
import com.coocaa.aries.jmeter.util.CmdExecLogUtil;
import com.coocaa.aries.jmeter.util.ExtTestCaseUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;

/**
 * @author : bijiahao
 * @date : 2019/3/27.
 * @description:
 */
public class StreamGobblerThread extends Thread {
    private static final Logger log = LoggerFactory.getLogger(StreamGobblerThread.class);
    /**
     * 执行完-成功信息
     */
    private static final String JMETER_EXEC_SUCCESS = "... end of run";

    InputStream is;

    String type;

    OutputStream os;

    private Integer id;

    public StreamGobblerThread(Integer id, InputStream is, String type) {
        this(id, is, type, null);
    }

    public StreamGobblerThread(Integer id, InputStream is, String type, OutputStream os) {
        super(id + "-" + type);
        this.id = id;
        this.is = is;
        this.type = type;
        this.os = os;
    }

    @Override
    public void run() {
        String line = null;
        BufferedReader reader = null;
        try {
            reader = new BufferedReader(new InputStreamReader(is, "utf-8"));
            while ((line = reader.readLine()) != null) {
                log.info(line);
                CmdExecLogUtil.add(id, line);
                if (StreamTypeConstants.isError(type)) {
                    ExtTestCaseUtil.updateStatusAndReportDir(id, "", ExecStatusEnums.ERROR.getCode());
                    ThreadExecMgr.set(false);
                    break;
                }
            }
            if (StreamTypeConstants.isStdOut(type) && CmdExecLogUtil.isContainInfo(id, JMETER_EXEC_SUCCESS)) {
                ExtTestCaseUtil.updateStatus(id, ExecStatusEnums.OK.getCode());
                ThreadExecMgr.set(false);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                reader.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
